<?php
/**
 * Created by PhpStorm.
 * User: eeo
 * Date: 2017/6/9
 * Time: 20:10
 */

namespace App\Http\Controllers\Marketing;


use App\Model\Marketing\Product;
use Illuminate\Http\Request;
use App\Model\Marketing\Order;
use App\Model\Foundation\Student;
use App\Model\System\Token;
use Illuminate\Support\Facades\DB;
use App\Model\Business\Appointment;
use Laravel\Lumen\Routing\Controller as BaseController;

use App\Http\Controllers\MessagePacket;


class OrderController extends BaseController
{
    use MessagePacket;

    function  __construct(){}

    /**
     * 按订单号获取订单
     * @param $id 订单id
     * @return packetMessage
     */
    function get($id)
    {
        $obj = Order::find($id);
        if($obj){
            if($obj->status == Order::UNPAID) {
                //超过48小时，则过期
                if(time() - $obj->orderdate > 172800){
                    $obj->status = Order::EXPIRED;
                }
                return $this->success($obj);
            }
        }
        return $this->fail($obj, '数据不存在');
    }
    

    /**
     * 管理员获取订单，查询条件如：学生id，status，单页记录数量
     * @param $request
     * @return packetMessage
     */
    function gets(Request $request){
        $query = Order::whereNotNull('id');
        if($request->has('status')){
            $status = $request->get('status');
            $query->where('status', $status);
        }

        $query->where(function ($query) use ($request){
            if($request->has('id')){
                $id = $request->get('id');
                $query->orwhere('id', $id);
            }
            if($request->has('productname')){
                $productname = $request->get('productname');
                $query->orwhere('productname','like', "%$productname%");
            }
            if($request->has('studentid')){
                $studentid = $request->get('studentid');
                $query->orwhere('studentid', $studentid);
            }
            if($request->has('mobile')){
                $mobile = $request->get('mobile');
                $query->orwhere('mobile', $mobile);
            }
        });
        $query->orderBy('orderdate', 'desc');
//        var_dump($query->toSql());exit();

        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if ($request->has('perPage')) {
                $limit = $request->get('perPage');
            }
            $info = $query->paginate($limit);
            $orders = $info->items();
        }else{
            $orders = $query->get();
        }

        foreach ($orders as $key => $order){
            //超过48小时，则过期
            if($order->status == Order::UNPAID) {
                if(time() - $order->orderdate > 172800) {
                    $order->status = Order::EXPIRED;
                }
            }
            $orders[$key] = $order;
        }
        # 需要／不需要 分页
        if($request->has('page')) {
            $info = $info->toarray();
            $data['list'] = $orders;
            unset($info['data']);
            $data['pager'] = $info;
        }else{
            $data = $orders;
        }

        if(empty($orders)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }


    /**
     * 获取某学生的订单，查询条件有：status，单页记录数量
     * @param $request
     * @return packetMessage
     */
    function getOrdersByStudentid(Request $request,$id){
        $id = intval($id);
        $query = Order::where('studentid', $id);
        if($request->has('status')){
            $status = $request->get('status');
            $query->where('status', $status);
        }

        # 需要／不需要 分页
        if($request->has('page')) {
            $limit = 30;
            if ($request->has('perPage')) {
                $limit = $request->get('perPage');
            }

            $orders = $query->orderBy('orderdate', 'desc')->paginate($limit)->toArray();
            foreach ($orders['data'] as $key => $order) {
                //超过48小时，则过期
                if ($order['status'] == Order::UNPAID) {
                    if (time() - $order['orderdate'] > 172800) {
                        $order['status'] = Order::EXPIRED;
                    }
                }
            }
            $data['list'] = $orders['data'];
            unset($orders['data']);
            $data['pager'] = $orders;
        }else{
            $orders = $query->orderBy('orderdate', 'desc')->get()->toArray();
            foreach ($orders as $key => $order) {
                //超过48小时，则过期
                if ($order['status'] == Order::UNPAID) {
                    if (time() - $order['orderdate'] > 172800) {
                        $order['status'] = Order::EXPIRED;
                    }
                }
            }
            $data = $orders;
        }

        if(empty($data)){
            return $this->fail($data, '数据不存在');
        }
        return $this->success($data);
    }
    

    /**
     * 添加一个
     * @param Request $request
     * @return packetMessage
     */
    function  create(Request $request)
    {
        $obj = new Order($request->all());
        $obj->id = base_convert(uniqid(),16,10);
        $obj->status = Order::UNPAID;
        $obj->orderdate = time();
        $obj->created_by = Token::user()->userid;
        $obj->updated_by = Token::user()->userid;
        if($obj->save()){
            return $this->success($obj);
        }else{
            return $this->fail(false,'保存失败');
        }
    }


    /**
     * 更新某个订单的价格
     * @param Request $request,$id:订单id
     * @return packetMessage
     */
    function  updatePrice(Request $request, $id)
    {
        $obj = Order::find($id);
        $obj->amount = $request->amount;
        $obj->updated_by = Token::user()->userid;
        if($obj->save()){
            return $this->success($obj);
        }else{
            return $this->fail(false,'保存失败');
        }
    }

    
    /**
     * 取消订单
     * @param $id
     * @return packetMessage
     */
    function  cancel($id)
    {
        $obj = Order::find($id);
        $obj->status = Order::CANCELLED;
        if($obj->save()){
            return $this->success(true);
        }else{
            return $this->fail(false, '失败');
        }
    }


    /**
     * 修改订单状态为确认支付
     * @param $id
     * @return packetMessage
     */
    function confirmPay($id){
        $obj = Order::find($id);
        $obj->status = Order::CONFIRMED;
        if($obj->save()){
            return $this->success(true);
        }else{
            return $this->fail(false, '失败');
        }
    }

    /**
     * 支付订单
     * @param $id
     * @return packetMessage
     */
    function  pay($id)
    {
        $obj = Order::find($id);
        $obj->status = Order::PAID;
        if($obj->save()){
            if($obj->type == 2){
                $appoint = new Appointment;
                $appoint->classhours = Product::where('id',$obj->productid)->value('schedules');
                $appoint->status = 0;
                $appoint->studentuid = $obj->studentid;
                $appoint->studentname = $obj->studentname;
                $appoint->mobile = $obj->mobile;
                $appoint->courseid = $obj->productid;
                $appoint->coursename = $obj->productname;
                $appoint->orderdate = $obj->orderdate;
                $appoint->description = $obj->description;
                $appoint->amount = $obj->amount;
                $appoint->orderid = $obj->id;
                $appoint->creator = Token::user()->username;
                $appoint->created_by = Token::user()->userid;
                $appoint->updated_by = Token::user()->userid;
                $appoint->save();
            }
            return $this->success(true);
        }
        else{
            return $this->fail(false, '失败');
        }
    }

    /**
     * 删除订单
     * @param $id
     * @return packetMessage
     */
    public function  delete($id){
        if(Order::destroy($id)){
            return $this->success(true);
        }
        return $this->fail(false,'删除失败');
    }


    /**
     * 获取未分班的订单学生信息
     * @param Request $request
     * @param $id
     * @return packetMessage
     */
    public function getAvalidClasseOrderStudents(Request $request, $id)
    {
        try{
            $productid = $id;
            $orders = Order::select('studentid')
                ->where('type', Order::CLASSE)
                ->where('productid', $productid)
                ->where('status', Order::PAID)
                ->get()->toarray();

            $studentids = [];
            foreach ($orders as $ord){
                $studentids[] = $ord['studentid'];
            }

            $students = Student::wherein('studentuid', $studentids)->get();

            return $this->success($students);
        }catch (\Exception $e){
            return $this->fail(false, '错误信息:'.$e->getMessage());
        }

    }

    /**
     * 获取未分班的约课订单学生
     * @param Request $request
     * @return packetMessage
     */
    public function getAvalidAppointOrderStudents(Request $request)
    {
        try{
            $students = Order::getAvalidAppointOrderStudents();
            return $this->success($students);
        }catch (\Exception $e){
            return $this->fail(false, '错误信息:'.$e->getMessage());
        }
    }

}